package com.holyn.guofang.view.my;

import android.content.Context;
import android.content.DialogInterface;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.apkfuns.logutils.LogUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.holyn.guofang.R;
import com.holyn.guofang.model.webhttp.HttpConfigure;
import com.holyn.guofang.model.webhttp.wo.BrandItemInfoWo;
import com.holyn.guofang.model.webhttp.wo.StatusWo;
import com.holyn.guofang.model.webhttp.wo.TaskWo;
import com.holyn.guofang.model.webhttp.wo.UserCardListWo;
import com.holyn.guofang.model.webhttp.wo.UserInfoWo;
import com.holyn.guofang.presenter.BaseView;
import com.holyn.guofang.presenter.brand.BrandContract;
import com.holyn.guofang.presenter.brand.BrandPresenter;
import com.holyn.guofang.utils.MD5Uitl;
import com.holyn.guofang.view.BaseActivity;
import com.holyn.guofang.view.distinguish.SearchResultListActivity;
import com.holyn.guofang.viewcommon.dialog.TaskPayDialog;
import com.holyn.guofang.viewcommon.itemdecoration.LinearLayoutItemDecoration;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreater;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Holyn on 2017/6/13.
 */

public class MyDealProcessActivity extends BaseActivity implements BaseView, BrandContract.MyDealProcessView, OnLoadmoreListener {
    private static final int REQUEST_ACTION_POST_TASK_LIST_FIRST = 0x0001;
    private static final int REQUEST_ACTION_POST_TASK_LIST_MORE = 0x0002;
    private static final int REQUEST_ACTION_POST_SEARCH_REULT_BY_TASK_ID = 0x0003;
    private static final int REQUEST_ACTION_POST_USER_INFO = 0x0004;
    private static final int REQUEST_ACTION_POST_USER_CARD_LIST = 0x0005;
    private static final int REQUEST_ACTION_POST_TASK_PAY_CODE = 0x0006;
    private static final int REQUEST_ACTION_POST_TASK_PAY = 0x0007;

    @BindView(R.id.rv_list)
    RecyclerView rvList;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    //获取任务列表的参数
    Integer pageSize = 20;
    Integer page = 1;

    //根据任务ID获取任务详情的参数
    Integer TaskID;
    String SortType = "";
    Integer BeginRow = 1;
    Integer EndRow = pageSize;

    BrandContract.Presenter presenter;

    private MyRecyclerAdapter recyclerAdapter;
    private List<TaskWo.DataBean.TaskListBean> taskBeanList = new ArrayList<>();

    private String unpay;
    private Integer curClickTaskId = 0;

    private TaskPayDialog passwordTaskPayDialog = null;
    private TaskPayDialog validCodeTaskPayDialog = null;

    @Override
    protected int getLayoutResID() {
        return R.layout.activity_my_deal_process;
    }

    @Override
    protected void onMyCreate() {
        ButterKnife.bind(this);
        showToolbar("未查看或处理中的任务");

        presenter = new BrandPresenter(this);
        presenter.addMyDealProcessView(this);
        presenter.postTaskList(REQUEST_ACTION_POST_TASK_LIST_FIRST, pageSize, page);

        refreshLayout.setOnLoadmoreListener(this);
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreater(new DefaultRefreshFooterCreater() {
            @NonNull
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                ClassicsFooter footer = new ClassicsFooter(context);
                footer.setBackgroundResource(android.R.color.white);
                footer.setSpinnerStyle(SpinnerStyle.Scale);//设置为拉伸模式
                return footer;//指定为经典Footer，默认是 BallPulseFooter
            }
        });
    }

    private void initRecyclerView(){
        recyclerAdapter = new MyRecyclerAdapter(taskBeanList);
        recyclerAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                curClickTaskId = taskBeanList.get(i).getTaskID();
                String state = taskBeanList.get(i).getState();
                if (state.equals("完成")){
                    TaskID = taskBeanList.get(i).getTaskID();
                    presenter.postUserInfo(REQUEST_ACTION_POST_USER_INFO);
                }
            }
        });
        rvList.setLayoutManager(new LinearLayoutManager(MyDealProcessActivity.this));
        rvList.addItemDecoration(new LinearLayoutItemDecoration(MyDealProcessActivity.this));
        rvList.setAdapter(recyclerAdapter);
    }


    @Override
    public void requestStart(Integer requestAction) {
        if (requestAction == REQUEST_ACTION_POST_USER_INFO){
            showLoadingDialog();
        } else if (requestAction == REQUEST_ACTION_POST_TASK_LIST_FIRST){
            showLoadingDialog();
        }  else if (requestAction == REQUEST_ACTION_POST_TASK_PAY_CODE){
            showLoadingDialog();
        } else if (requestAction == REQUEST_ACTION_POST_TASK_PAY){
            showLoadingDialog();
        }
    }

    @Override
    public void requestError(Integer requestAction, Throwable e) {
        toastMsg("出现异常");
        closeLoadingDialog();
        refreshLayout.finishLoadmore();
    }

    @Override
    public void requestComplete(Integer requestAction) {
        refreshLayout.finishLoadmore();
    }

    @Override
    public void responseSuccess(int requestAction, TaskWo taskWo) {
        if (taskWo.getStatus() == HttpConfigure.STATUS_SUCCESS){
            unpay = taskWo.getUnpay();
            List<TaskWo.DataBean.TaskListBean> taskList  = taskWo.getData().getTaskList();
            if (taskList == null){
                refreshLayout.setLoadmoreFinished(true);
            } else {
                if (taskList.size() == 0){
                    refreshLayout.setLoadmoreFinished(true);
                } else {
                    if (requestAction == REQUEST_ACTION_POST_TASK_LIST_FIRST){
                        taskBeanList.clear();
                        taskBeanList.addAll(taskList);
                        initRecyclerView();
                    } else if (requestAction == REQUEST_ACTION_POST_TASK_LIST_MORE){
                        taskList.addAll(taskList);
                        recyclerAdapter.notifyDataSetChanged();
                    }
                }
            }

        } else {
            toastMsg("获取任务列表失败");
        }
        closeLoadingDialog();
    }

    @Override
    public void responseSuccess(int requestAction, UserInfoWo userInfoWo) {
        if (userInfoWo.getStatus() == HttpConfigure.STATUS_SUCCESS){
            UserInfoWo.UserInfoBean.UserCardBean cardBean = userInfoWo.getUserInfo().getUserCard();
            if (cardBean == null){//代表卡已过期
                presenter.postUserCardList(REQUEST_ACTION_POST_USER_CARD_LIST, 2, -1, -1);//请求后只做提示
            } else {//未过期
                if (unpay.contains(String.valueOf(curClickTaskId))){
                    int validMethod = cardBean.getValidMethod();
                    if (validMethod == 0){//弹出dialog，输入支付密码，再支付
                        closeLoadingDialog();
                        showPasswordTaskPayDialog();
                    } else if (validMethod == 1){//弹出dialog，输入验证码，再支付
                        closeLoadingDialog();
                        showValidCodeTaskPayDialog();
                    } else if (validMethod == 2){//直接支付
                        presenter.postTaskPay(REQUEST_ACTION_POST_TASK_PAY, curClickTaskId, "");
                    }
                } else {
                    presenter.postSearchResultByTaskID(REQUEST_ACTION_POST_SEARCH_REULT_BY_TASK_ID, TaskID, SortType, BeginRow, EndRow);
                }
            }
        } else {
            closeLoadingDialog();
            toastMsg("获取用户详情失败");
        }
    }

    @Override
    public void responseSuccess(int requestAction, UserCardListWo userCardListWo) {
        if (userCardListWo.getStatus() == HttpConfigure.STATUS_SUCCESS){
            List<UserCardListWo.DataBean> dataBeanList = userCardListWo.getData();
            if (dataBeanList == null){
                toastMsg("当前国方卡已过期，请前往 我的-购国方卡 购卡");
            } else {
                if (dataBeanList.size() == 0){
                    toastMsg("当前国方卡已过期，请前往 我的-购国方卡 购卡");
                } else {
                    toastMsg("当前国方卡已过期，请前往 我的-用卡管理 激活卡");
                }
            }
        } else {
            toastMsg("获取获取用户的国方卡信息失败");
        }
        closeLoadingDialog();
    }

    /**
     * 2.4.17 获取任务支付验证码、 2.4.18 任务支付
     */
    @Override
    public void responseSuccess(int requestAction, StatusWo statusWo) {
        if (requestAction == REQUEST_ACTION_POST_TASK_PAY_CODE){
            if (statusWo.getStatus() == HttpConfigure.STATUS_SUCCESS){
                toastMsg("成功发送支付验证码");
            } else {
                toastMsg("发送支付验证码失败");
            }
            closeLoadingDialog();
        } else if (requestAction == REQUEST_ACTION_POST_TASK_PAY){
            if (statusWo.getStatus() == HttpConfigure.STATUS_SUCCESS){
                unpay.replace(String.valueOf(curClickTaskId), "");
                presenter.postSearchResultByTaskID(REQUEST_ACTION_POST_SEARCH_REULT_BY_TASK_ID, TaskID, SortType, BeginRow, EndRow);
            } else {
                toastMsg("支付失败");
                closeLoadingDialog();
            }
        }
    }

    @Override
    public void responseSuccess(int requestAction, BrandItemInfoWo brandItemInfoWo) {
        LogUtils.d(brandItemInfoWo);
        if (brandItemInfoWo.getStatus() == HttpConfigure.STATUS_SUCCESS){
            List<BrandItemInfoWo.DataBean.ResultBean> resultBeanList = brandItemInfoWo.getData().getResult();
            if (resultBeanList == null){
                toastMsg("没对应的查询结果");
            } else {
                if (resultBeanList.size() == 0){
                    toastMsg("没对应的查询结果");
                } else {
                    SearchResultListActivity.start(MyDealProcessActivity.this, brandItemInfoWo, TaskID);
                }
            }
        } else {
            toastMsg("获取任务详情失败");
        }
        closeLoadingDialog();
    }

    @Override
    public void onLoadmore(RefreshLayout refreshLayout) {
        page++;
        presenter.postTaskList(REQUEST_ACTION_POST_TASK_LIST_MORE, pageSize, page);
    }

    private void showPasswordTaskPayDialog(){
        if (passwordTaskPayDialog == null){
            passwordTaskPayDialog = new TaskPayDialog(MyDealProcessActivity.this, TaskPayDialog.STATUS_PASSWORD,
                    new TaskPayDialog.OnSureClickListener(){

                        @Override
                        public void onSureClick(String value) {
                            presenter.postTaskPay(REQUEST_ACTION_POST_TASK_PAY, curClickTaskId, MD5Uitl.getMd5Value(value));
                            passwordTaskPayDialog.dismiss();
                        }
                    });
        }
        passwordTaskPayDialog.show();
    }

    private void showValidCodeTaskPayDialog(){
        if (validCodeTaskPayDialog == null){
            validCodeTaskPayDialog = new TaskPayDialog(MyDealProcessActivity.this, TaskPayDialog.STATUS_VALID_CODE,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            presenter.postTaskPayCode(REQUEST_ACTION_POST_TASK_PAY_CODE);
                        }
                    },
                    new TaskPayDialog.OnSureClickListener() {
                        @Override
                        public void onSureClick(String value) {
                            presenter.postTaskPay(REQUEST_ACTION_POST_TASK_PAY, curClickTaskId, value);
                            validCodeTaskPayDialog.dismiss();
                        }
                    });
        }
    }

    private class MyRecyclerAdapter extends BaseQuickAdapter<TaskWo.DataBean.TaskListBean, BaseViewHolder>{
        public MyRecyclerAdapter(@Nullable List<TaskWo.DataBean.TaskListBean> data) {
            super(R.layout.item_my_deal_process, data);
        }

        @Override
        protected void convert(BaseViewHolder baseViewHolder, TaskWo.DataBean.TaskListBean taskListBean) {
            baseViewHolder.setText(R.id.tv_task_type, taskListBean.getTaskType());
            baseViewHolder.setText(R.id.tv_sub_time, taskListBean.getSubTime());
            baseViewHolder.setText(R.id.tv_finish_time, taskListBean.getFinishTime());
            String state = taskListBean.getState();
            TextView tvStatus = baseViewHolder.getView(R.id.tv_status);
            if (state.equals("完成")){
                baseViewHolder.setText(R.id.tv_status, "查看>");
                tvStatus.setBackgroundResource(R.drawable.selector_bg_primary_cor2_sol);
            } else {
                baseViewHolder.setText(R.id.tv_status, "正在处理");
                tvStatus.setBackgroundResource(R.drawable.shape_bg_orange_cor2_sol);
            }

        }
    }
}
